#############################################################################

#     Regression method for mediation analysis               
#     Applicable situation:
#         1.The outcome is dichotomous data;
#         2.An exposure variable and two covariates: dichotomous data;
#         2.Two parallel mediators: continuous or dichotomous data.

#############################################################################
regression<-function(Data){
  #The full model:
  logitmodel<- glm(Y~A+M1+M2+C1+C2,data = Data,family = "binomial")
  
  #The direct effect
  DE<-as.character(coef(summary(logitmodel))[2,1])
  DE<-as.numeric(DE)
  theta1<-as.character(coef(summary(logitmodel))[3,1])
  theta1<-as.numeric(theta1)
  theta2<-as.character(coef(summary(logitmodel))[4,1])
  theta2<-as.numeric(theta2)
  
  #The first mediation model:
  if(all(unique(Data$M1)%in%c(0,1))){
    logitmodel_m1<- glm(M1~A+C1+C2,data = Data,family = "binomial")
    beta1<-as.character(coef(summary(logitmodel_m1))[2,1])
    beta1<-as.numeric(beta1)
  }else{
    linearmodel_m1<-glm(M1~A+C1+C2,data = Data,family = "gaussian")
    beta1<-as.character(coef(summary(linearmodel_m1))[2,1])
    beta1<-as.numeric(beta1)
  }
  
  #The second mediation model:
  if(all(unique(Data$M2)%in%c(0,1))){
    logitmodel_m2<- glm(M2~A+C1+C2,data = Data,family = "binomial")
    beta2<-as.character(coef(summary(logitmodel_m2))[2,1])
    beta2<-as.numeric(beta2)
  }else{
    linearmodel_m2<-glm(M2~A+C1+C2,data = Data,family = "gaussian")
    beta2<-as.character(coef(summary(linearmodel_m2))[2,1])
    beta2<-as.numeric(beta2)
  }
  
  #The indirect effect
  IE1<-theta1*beta1
  IE2<-theta2*beta2
  
  result<-data.frame(DE,IE1,IE2)
  return(result)
}
